package com.shawn.server.service;

import cn.hutool.core.collection.CollUtil;
import com.shawn.autoconfig.template.EMTemplate;
import com.shawn.commons.utils.CommentType;
import com.shawn.commons.utils.RC;
import com.shawn.dubbo.api.*;
import com.shawn.model.entity.Announcement;
import com.shawn.model.entity.User;
import com.shawn.model.entity.UserInfo;
import com.shawn.model.mongo.Comment;
import com.shawn.model.mongo.Friend;
import com.shawn.model.vo.*;
import com.shawn.server.exception.BusinessException;
import com.shawn.server.interceptor.ThreadContext;
import io.jsonwebtoken.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessageService {

    @Autowired
    private EMTemplate emTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    @DubboReference
    private CommentsApi commentsApi;


    public UserInfoVo getUserInfoByHXId(String hxId) {

        log.info("接收到环信id:{}" + hxId);
        User user = userApi.getUserByHXId(hxId);

        UserInfo userInfo = userInfoApi.findDetailById(user.getId());
        if (userInfo == null) {
            return new UserInfoVo();
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        //仅复制同名属性
        BeanUtils.copyProperties(userInfo, userInfoVo);
        //给不同类型属性复制
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    public void addFriend(Long friendId) {
        Long userId = ThreadContext.getUserId();
        boolean res = emTemplate.addFriend(RC.HX_USER_PREFIX + userId, RC.HX_USER_PREFIX + friendId);
        if (!res) {
            throw new BusinessException(ErrorResult.error());
        }
        //将朋友关系保存至mongoDB
        friendApi.save(userId, friendId);
    }

    public PageResult<ContactVo> getFriendsPage(Integer page, Integer pageSize, String nickname) {
        Long userId = ThreadContext.getUserId();
        //查询所有朋友id
        List<Friend> friends = friendApi.getAllById(userId);
        if (friends.size() == 0) {
            return new PageResult<>();
        }
        List<Long> ids = friends.stream().map(Friend::getFriendId).collect(Collectors.toList());
        UserInfo userInfo = new UserInfo();
        if (!StringUtils.isEmpty(nickname)) {
            userInfo.setNickname(nickname);
        }
        //获取分页查询结果
        PageResult<UserInfo> userInfoPageResult = userInfoApi.findByIds(ids, userInfo, page, pageSize);
        //转化成vo对象返回给前端
        List<ContactVo> contactVos = new ArrayList<>();
        List<UserInfo> userInfos = userInfoPageResult.getItems();
        for (UserInfo info : userInfos) {
            ContactVo contactVo = ContactVo.init(info);
            contactVos.add(contactVo);
        }
        return new PageResult<>(page, pageSize, userInfoPageResult.getCounts(), contactVos);
    }

    /**
     * 分页查询所有公告
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @return {@link PageResult}<{@link AnnouncementVo}>
     */
    public PageResult<AnnouncementVo> getAllAnnouncement(Integer page, Integer pageSize) {
        //调用公告Api
        PageResult<Announcement> pageResult = announcementApi.getAnnouncementByPage(page, pageSize);
        if (pageResult==null){
            return new PageResult<>();
        }
        //批量转换
        List<Announcement> announcements = pageResult.getItems();
        ArrayList<AnnouncementVo> announces = new ArrayList<>();
        for (Announcement ann : announcements) {
            AnnouncementVo vo = AnnouncementVo.init(ann);
            announces.add(vo);
        }
        return new PageResult<>(page,pageSize,pageResult.getCounts(),announces);
    }

    /**
     * 根据用户id获取所有点赞或喜欢评论的用户
     *
     * @param userId   用户id
     * @param page     页面
     * @param pageSize 页面大小
     * @param love     爱
     * @return {@link PageResult}<{@link AnnouncementVo}>
     */
    public PageResult<MessageVo> getCommentsUsers(Long userId, Integer page, Integer pageSize, CommentType commentType) {
        //调用公告Api
        PageResult<Comment> pageResult = commentsApi.getAllCommentsByUserId(userId,page,pageSize,commentType);
        if (pageResult.getCounts()==0){
            return new PageResult<>();
        }
        //批量转换
        List<Comment> comments = pageResult.getItems();
        //获取所有用户id
        List<Long> ids = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
        List<UserInfo> userInfos = userInfoApi.findByIds(ids);
        Map<Long, UserInfo> userInfoMap = CollUtil.fieldValueMap(userInfos, "id");
        ArrayList<MessageVo> messageVos = new ArrayList<>();
        for (Comment comment : comments) {
            MessageVo vo = MessageVo.init(comment,userInfoMap.get(comment.getUserId()));
            messageVos.add(vo);
        }
        return new PageResult<>(page,pageSize,pageResult.getCounts(),messageVos);
    }
}
